package cn.wy.user.service.impl;

import cn.wy.basic.util.Md5Utils;
import cn.wy.basic.util.StrUtils;
import cn.wy.exception.BusinessException;
import cn.wy.org.mapper.EmployeeMapper;
import cn.wy.user.domain.Logininfo;
import cn.wy.user.domain.User;
import cn.wy.user.mapper.LogininfoMapper;
import cn.wy.user.mapper.UserMapper;
import cn.wy.basic.service.impl.BaseServiceImpl;
import cn.wy.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    @Transactional
    public void insert(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);


        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.insert(logininfo);
        user.setLogininfoId(logininfo.getId());
        super.insert(user);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        User user = userMapper.findOne(id);
        logininfoMapper.delete(user.getLogininfoId());
        super.delete(id);
    }

    @Override
    @Transactional
    public void update(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        User oldUser = userMapper.findOne(user.getId());
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        Logininfo oldLogininfo = logininfoMapper.findOne(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user, oldLogininfo);
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }

    @Override
    @Transactional
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String confirmPwd = map.get("confirmPwd");
        //一：校验：空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
                ||StringUtils.isEmpty(pwd) || StringUtils.isEmpty(confirmPwd)){
            throw new BusinessException("信息不能为空!!!");
        }

        //二：校验：密码是否一致
        if(!pwd.equals(confirmPwd)){
            throw new BusinessException("两次密码不一致");
        }

        //三：手机验证码：是否过期，是否正确
        Object redisPhoneCode = redisTemplate.opsForValue().get("register:" + phone);
        if(redisPhoneCode == null){
            throw new BusinessException("手机验证码过期，请重新获取!!!");
        }
        if(!phoneCode.equals(redisPhoneCode.toString().split(":")[0])){  // code:时间戳
            throw new BusinessException("手机验证码错误!!!");
        }

        //四：添加到数据库
        User user = map2User(phone,pwd);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加logininfo信息 - 自增ID
        logininfoMapper.insert(logininfo);
        //2.再将自增ID设置到user中吗，再添加user表
        user.setLogininfoId(logininfo.getId());
        userMapper.insert(user);
    }

    /**
     * 邮箱注册
     * @param map
     */
    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String password = map.get("password");
        String pwdRepeat = map.get("pwdRepeat");
//        空值校验
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password)
                ||StringUtils.isEmpty(pwdRepeat)){
            throw new BusinessException("信息不能为空!!!");
        }
//        密码是否一致
        if(!password.equals(pwdRepeat)){
            throw new BusinessException("两次密码不一致");
        }
//        邮箱是否已注册
        User user = userMapper.findUserByEmail(email);
        if(user!=null){
            throw new BusinessException("该邮箱已注册，请直接前往登录！");
        }

        User user1 = new User();
        user1.setUsername(email);
        user1.setEmail(email);
        String salt = StrUtils.getComplexRandomString(32);
        user1.setPassword(salt);
        String md5Pwd = Md5Utils.encrypByMd5(password+salt);
        user1.setPassword(md5Pwd);
        user1.setState(1);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user1, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.insert(logininfo);
        user1.setLogininfoId(logininfo.getId());

//3.发送邮件：告诉店铺管理员激活邮件使用
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("2218180746@qq.com");
        helper.setSubject("账号激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>你的账号已经注册!!!</h1><img src='http://123.207.27.208' ><a href='http://localhost:8080/user/active/'>点击该链接激活</a>",
                true);
        //收件人
        helper.setTo(email);
        javaMailSender.send(mimeMessage);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo= new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User map2User(String phone, String pwd) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = Md5Utils.encrypByMd5(pwd+salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }
}
